﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Medical.INFS;
using Sector7.Medical.INFM.Windows;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Framework.Utility;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using System.ComponentModel;
using Sector7.Medical.EntityType;

namespace Sector7.Medical.INFM.Controls
{
    /// <summary>
    /// SickBedSummaryControl.xaml 的交互逻辑
    /// </summary>
    public partial class SickBedSummaryControl : AddModeControlBase
    {
        #region Accessor
        #endregion

        #region Public Functions
        #endregion

        #region Private Functions
        private void SickBedSummaryControl_Loaded(object obj, RoutedEventArgs e)
        {
            m_crud = CrudType.Unknown;

            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

            //SwitchPropertiyGroupsEnabledState(false);
            //SwitchPropertiyActionButtonsState(CrudType.Unknown);
            //SwitchActionButtonsState(true);

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(LoadData_DoWork);
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 加载数据工作线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadData_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            GetData();

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        /// <summary>
        /// 读取所有病床相关信息的列表
        /// </summary>
        private void GetData()
        {
            //1.获取所有病床信息列表
            m_sickBedList = Agent_INFS.GetSickBedList();

            //2.获取所有病区信息列表
            m_sickAreaList = Agent_INFS.GetSickAreaList();

            //3.获取所有病床等级信息列表
            m_sickBedLevelList = Agent_INFS.GetSickBedLevelList();

            //4.获取所有病房信息列表
            m_sickRoomList = Agent_INFS.GetSickRoomList();

            //5.获取所有科室列表
            m_deptList = Agent_INFS.GetDepartmentList(C_DepartmentFlags.SUB_DEPARTMENT);
            m_tempBedList.AddRange(m_sickBedList);

        }

        /// <summary>
        /// 加载所有病床数据
        /// </summary>
        private void LoadData()
        {
            trvMain.Items.Clear();

            foreach (var sickAreaType in m_sickAreaList)
            {
                trvMain.Items.Add(CreateSickAreaNode(sickAreaType));

                if (m_deptList != null)
                { 
                
                }
            }

            ClientUtil.LoadItemsSource(dtgMain, m_sickBedList);

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 切换按钮状态
        /// </summary>
        /// <param name="crud"></param>
        private void SwitchSickBedPropertyActionButtonsState(CrudType crud)
        {
            switch (crud)
            {
                case CrudType.Create:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
                case CrudType.Read:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = true;
                    btnDelete.IsEnabled = true;
                    break;
                default:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
            }
        }

        /// <summary>
        /// 创建病区节点
        /// </summary>
        /// <param name="area"></param>
        /// <returns></returns>
        private TreeViewItem CreateSickAreaNode(M7_SickArea area)
        {
            var areaNode = new TreeViewItem();
            areaNode.Margin = new Thickness(0, 3, 0, 3);
            areaNode.Header = area.AreaName;
            areaNode.Name = "area";
            areaNode.Tag = area;

            if (m_deptList != null)
            {
                foreach (var deptType in m_deptList)
                {
                    areaNode.Items.Add(CreateSickDeptNode(deptType));
                }
            }

            return areaNode;
        }

        private TreeViewItem CreateSickDeptNode(M7_Department dept)
        {
            var deptNode = new TreeViewItem();
            deptNode.Margin = new Thickness(0, 3, 0, 3);
            var deptItem = dept.DeptName +  "[病房(...),病床(...)]";
            deptNode.Header = deptItem;
            deptNode.Name = "dept";
            deptNode.Tag = dept;

            return deptNode;
        }

        /// <summary>
        /// 点击树事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trvMain_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            SelectTreeViewItem(selectedTypeNode);
        }

        private void SelectTreeViewItem(TreeViewItem selectedTypeNode)
        {
            Senvironments.ProgressWindow.Visibility = Visibility.Visible;
            int areaId = 0;
            int deptId = 0;

            if (selectedTypeNode != null)
            {
                selectedTypeNode.IsSelected = true;
                var selectedName = selectedTypeNode.Name;
                SwitchSickBedPropertyActionButtonsState(CrudType.Read);
                ClientUtil.UnLoadItemsSource(dtgMain);

                switch (selectedName)
                {
                    case "area":
                        var tag = selectedTypeNode.Tag as M7_SickArea;
                        areaId = tag.AreaId;
                        m_currentBedList = Agent_INFS.GetSickBedListByAreaId(areaId);
                        break;
                    case "dept":
                        var parentItem = selectedTypeNode.Parent as TreeViewItem;
                        areaId = (parentItem.Tag as M7_SickArea).AreaId;
                        deptId = (selectedTypeNode.Tag as M7_Department).DeptId;
                        m_currentBedList = Agent_INFS.GetSickBedListByAreaDeptId(areaId, deptId);
                        break;
                    default:
                        break;
                }

                var getBedtListWorker = BackgroundWorkerUtil.GetWorker(this);
                getBedtListWorker.DoWork += new DoWorkEventHandler(getBedListWorker_DoWork);
                getBedtListWorker.RunWorkerAsync(1);

            }
            else
            {
                SwitchSickBedPropertyActionButtonsState(CrudType.Unknown);
            }
        }

        private void LoadBedList()
        {
            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            string header = selectedTypeNode.Header.ToString();
            string replaceStr = "...";
            string splitChar = ",";

            if (header.Contains(splitChar))
            {
                string[] headerSplit = header.Split(
                    new string[] {splitChar}, StringSplitOptions.RemoveEmptyEntries);

                selectedTypeNode.Header = headerSplit[0].
                    Replace(replaceStr, m_sickRoomList.Count.ToString())
                    + splitChar
                    + headerSplit[1].Replace(replaceStr, m_currentBedList.Count.ToString());
            }

            ClientUtil.LoadItemsSource(dtgMain, m_currentBedList);

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        private void getBedListWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadBedList));
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object obj, RoutedEventArgs e)
        {
            var addSickBedWindow = new AddSickBedWindow();
            addSickBedWindow.InitializeWindow(CrudType.Create);
            addSickBedWindow.AddSuccess += new EventHandler(AddSickBedWindow_AddSuccess);
            addSickBedWindow.ShowDialog();
        }

        private void AddSickBedWindow_AddSuccess(object sender, EventArgs e)
        {
            int result = 0;
            var addSickBedWindow = sender as AddSickBedWindow;
            M7_SickBed sickBed = addSickBedWindow.SickBed;

            switch (addSickBedWindow.Crud)
            {
                case CrudType.Create:
                    object bedIdObj = Agent_INFS.AddSickBed(sickBed);
                    if (bedIdObj != null)
                    {
                        sickBed.BedId = Convert.ToInt32(bedIdObj);
                        m_sickBedList.Add(sickBed);
                    }
                    SelectRoomItem(sickBed);
                    dtgMain.Items.Refresh();
                    break;
                case CrudType.Update:
                    result = Agent_INFS.UpdateSickBed(sickBed);
                    dtgMain.Items.Refresh();
                    break;
                default:
                    break;
            }
        }

        protected override void InitializeForUpdating()
        {
            base.InitializeForUpdating();
        }

        /// <summary>
        /// 选中Item颜色改变
        /// </summary>
        /// <param name="area"></param>
        private void SelectRoomItem(M7_SickBed bed)
        {
            if (dtgMain.Items.Contains(bed))
            {
                dtgMain.SelectedItem = bed;
            }
        }

        private void DoModify()
        {
            var selectedBed = dtgMain.SelectedItem as M7_SickBed;
            if (selectedBed != null)
            {
                var addSickBedWindow = new AddSickBedWindow();
                addSickBedWindow.SickBed = selectedBed;
                addSickBedWindow.InitializeWindow(CrudType.Update);
                addSickBedWindow.AddSuccess += new EventHandler(AddSickBedWindow_AddSuccess);
                addSickBedWindow.ShowDialog();
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void btnModify_Click(object obj, RoutedEventArgs e)
        {
            DoModify();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object obj, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem is M7_SickBed)
            {
                MessageBoxResult mbr = Alert.ShowDialog(AlertType.Question, "是否确定删除该病床?");
                if (mbr == MessageBoxResult.Yes)
                {
                    M7_SickBed bed = dtgMain.SelectedItem as M7_SickBed;
                    int ret = Agent_INFS.DeleteSickBed(bed.BedId);
                    if (ret > 0)
                    {
                        if (m_sickBedList.Contains(bed))
                        {
                            int index = dtgMain.Items.IndexOf(bed);
                            index++;

                            m_sickBedList.Remove(bed);
                            dtgMain.Items.Refresh();

                            if (dtgMain.Items.Count != 0)
                            {
                                while (index >= dtgMain.Items.Count)
                                {
                                    index--;
                                }
                                dtgMain.SelectedIndex = index;
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region Structure
        public SickBedSummaryControl()
        {
            InitializeComponent();
        }
        #endregion

        #region Inner Members
        /// <summary>
        /// 获取所有病房信息
        /// </summary>
        private List<M7_SickBed> m_sickBedList;

        /// <summary>
        /// 获取临时病房信息列表
        /// </summary>
        private List<M7_SickBed> m_tempBedList = new List<M7_SickBed>();

        /// <summary>
        /// 获取当前病房信息列表
        /// </summary>
        private List<M7_SickBed> m_currentBedList = new List<M7_SickBed>();

        /// <summary>
        /// 获取所有病区列表
        /// </summary>
        private List<M7_SickArea> m_sickAreaList;

        /// <summary>
        /// 获取所有病床等级信息列表
        /// </summary>
        private List<M7_SickBedLevel> m_sickBedLevelList;

        /// <summary>
        /// 获取所有病房列表
        /// </summary>
        private List<M7_SickRoom> m_sickRoomList;

        /// <summary>
        /// 获取所有科室列表
        /// </summary>
        private List<M7_Department> m_deptList;
        #endregion
    }
}
